<script>
import {
  create,
  getRoleIds,
  giveRole,
  page,
  remove,
  resetPassword,
  update,
  updateStatus
} from "@/views/superAdmin/admin/api";
import { globalLoading, isNull } from "@/utils/service";
import { options as roleOptions } from "@/views/superAdmin/role/api";
import { hasPermission } from "@/utils/auth";

export default {
  name: "admin",
  data() {
    let _vm = this;
    return {
      table: {
        pageNo: 1,
        pageSize: 10,
        pages: 0,
        total: 0,
        data: [],
        loading: true
      },
      query: {
        account: "",
        name: "",
        remark: ""
      },
      dialog: {
        title: "创建账号",
        visible: false,
        form: {
          id: undefined,
          name: "",
          account: "",
          password: "",
          rePassword: "",
          email: "",
          remark: ""
        },
        rules: {
          name: [
            { required: true, message: "请输入用户名称", trigger: "blur" },
            { min: 1, max: 20, message: "长度在 1 - 20 个字符", trigger: "blur" }
          ],
          account: [
            {
              validator: (rule, value, callback) => {
                if (_vm.isUpdateAdminInfo) {
                  callback();
                }
                if (isNull(value)) {
                  callback(new Error("请输入登录账号"));
                }
                if (value.length < 4 || value.length > 30) {
                  callback(new Error("长度在 4 - 30 个字符之间"));
                }
                callback();
              },
              trigger: "blur"
            }
          ],
          password: [
            {
              validator: (rule, value, callback) => {
                if (_vm.isUpdateAdminInfo) {
                  callback();
                }
                if (isNull(value)) {
                  callback(new Error("请输入登录密码"));
                }
                if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)) {
                  callback(new Error("密码必须由数字、字母两种字符组成，长度在6-20位之间"));
                }
                callback();
              },
              trigger: "blur"
            }
          ],
          rePassword: [
            {
              validator: (rule, value, callback) => {
                if (_vm.isUpdateAdminInfo) {
                  callback();
                }
                if (isNull(value)) {
                  callback(new Error("请输入确认密码"));
                }
                if (_vm.dialog.form.password !== value) {
                  callback(new Error("两次密码内容不符合"));
                }
                callback();
              }, trigger: "blur"
            }
          ],
          email: [
            { required: true, message: "邮箱不能为空", trigger: "blur" },
            { type: "email", message: "请输入有效的邮箱地址", trigger: "blur" }
          ]
        }
      },
      dialog1: {
        visible: false,
        title: "重置密码",
        form: {
          adId: undefined,
          password: "",
          rePassword: ""
        },
        rules: {
          password: [
            {
              validator: (rule, value, callback) => {
                if (isNull(value)) {
                  callback(new Error("请输入登录密码"));
                }
                if (!/^(?![0-9]+$)(?![a-zA-Z]+$)[0-9A-Za-z]{6,20}$/.test(value)) {
                  callback(new Error("密码必须由数字、字母两种字符组成，长度在6-20位之间"));
                }
                callback();
              },
              trigger: "blur"
            }
          ],
          rePassword: [
            {
              validator: (rule, value, callback) => {
                if (isNull(value)) {
                  callback(new Error("请输入确认密码"));
                }
                if (_vm.dialog1.form.password !== value) {
                  callback(new Error("两次密码内容不符合"));
                }
                callback();
              }, trigger: "blur"
            }
          ]
        }
      },
      dialog2: {
        title: "分配角色",
        visible: false,
        adName: "",
        adAccount: "",
        options: [],
        form: {
          adId: undefined,
          roleIds: []
        }
      }
    };
  },
  computed: {
    isUpdateAdminInfo() {
      return !isNull(this.dialog.form.id);
    }
  },
  created() {
    this.page();
  },
  methods: {
    hasPermission,
    page() {
      if (!hasPermission("admin.query")) {
        this.$message.warning("您没有获取当前表格数据的权限");
        return;
      }
      this.table.loading = true;
      let params = {
        pageNo: this.table.pageNo,
        pageSize: this.table.pageSize,
        account: this.query.account,
        name: this.query.name,
        remark: this.query.remark
      };
      page(params).then(r => {
        this.table.pages = r.pages;
        this.table.total = r.total;
        this.table.data = r.list;
      }).catch(err => {
          console.log(err);
        }
      ).finally(f => {
        this.table.loading = false;
      });
    },
    pageChange(v) {
      this.table.pageNo = v;
      this.page();
    },
    queryReset() {
      this.query.account = "";
      this.query.name = "";
      this.query.remark = "";
      this.page();
    },
    handleCreate() {
      this.dialog.form.id = undefined;
      this.dialog.form.name = "";
      this.dialog.form.account = "";
      this.dialog.form.remark = "";
      this.dialog.form.password = "";
      this.dialog.form.email = ""
      this.dialog.visible = true;
      this.dialog.title = "创建账号";
    },
    handleUpdate(row) {
      this.dialog.form.id = row.id;
      this.dialog.form.name = row.name;
      this.dialog.form.remark = row.remark;
      this.dialog.form.email = row.email
      this.dialog.visible = true;
      this.dialog.title = "编辑账号";
    },
    handleResetPwd(id) {
      this.dialog1.form.adId = id;
      this.dialog1.form.password = "";
      this.dialog1.form.rePassword = "";
      this.dialog1.visible = true;
    },
    async handleGiveRole(row) {
      await roleOptions().then(r => {
        this.dialog2.options = r;
      }).catch(e => {
        this.$message.warning(`获取角色选项失败:${e.message}`);
      });
      await getRoleIds(row.id).then(r => {
        this.dialog2.form.roleIds = r;
      }).catch(e => {
        this.$message.warning(`获取管理员所有角色失败:${e.message}`);
      });
      this.dialog2.form.adId = row.id;
      this.dialog2.adName = row.name;
      this.dialog2.adAccount = row.account;
      this.dialog2.visible = true;
    },
    handleDropdown(v, row) {
      switch (v) {
        case "重置密码":
          this.handleResetPwd(row.id);
          break;
        case "分配角色":
          this.handleGiveRole(row);
          break;
        case "删除账号":
          this.$confirm("确认删除该账号吗?", "提示", {
            distinguishCancelAndClose: true,
            confirmButtonText: "确认",
            cancelButtonText: "取消"
          })
            .then(() => {
              remove(row.id).then(r => {
                this.$message.success("删除成功");
                this.page();
              }).catch(e => {
                this.$message.error(`删除账号错误 : ${e.message}`);
              });
            });
          break;
        default:
          break;
      }
    },
    updateStatusChange(row) {
      let loading = globalLoading(this);
      updateStatus(row.id, row.status).then(r => {
        this.$message.success("修改状态成功");
        this.page();
      }).catch(e => {
          console.log(e);
        }
      ).finally(() => loading.close());
    },
    commit() {
      let flag = false;
      this.$refs.dialogForm.validate((valid) => flag = valid);
      if (!flag) {
        return;
      }
      let loading = globalLoading(this);
      if (this.dialog.form.id) {
        update(this.dialog.form).then(r => {
          this.$message.success("操作成功");
          this.page();
          this.dialog.visible = false;
        }).catch(e => {
          console.log(e.message);
        }).finally(() => {
          loading.close();
        });
      } else {
        create(this.dialog.form).then(r => {
          this.$message.success("操作成功");
          this.page();
          this.dialog.visible = false;
        }).catch(e => {
          console.log(e.message);
        }).finally(() => {
          loading.close();
        });
      }
    },
    reqResetPwd() {
      let flag;
      this.$refs.resetPwdForm.validate((valid) => flag = valid);
      if (!flag) {
        return;
      }
      resetPassword(this.dialog1.form).then(r => {
        this.$message.success("操作成功");
        this.dialog1.visible = false;
      }).catch(e => {
        console.log(e.message);
      });
    },
    reqGiveRole() {
      giveRole(this.dialog2.form).then(() => {
        this.$message.success("操作成功");
        this.dialog2.visible = false;
      }).catch(r => {
        this.$message.error(`分配角色失败 : ${r.message}`);
      });
    }
  }
};
</script>

<template>
  <div style="margin: 10px">
    <div class="header">
      <div>
        <el-form :model="query" ref="query" :inline="true" size="mini">
          <el-form-item label="账号" prop="account">
            <el-input v-model="query.account" placeholder="请输入账号(精确)" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="query.name" placeholder="请输入用户名称(包含)" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input v-model="query.remark" placeholder="请输入备注(包含)" style="width: 250px"></el-input>
          </el-form-item>
          <el-form-item>
            <el-button type="primary" @click="page">搜索</el-button>
            <el-button type="info" @click="queryReset">重置</el-button>
          </el-form-item>
        </el-form>
      </div>
      <div>
        <el-button
          v-permission="'admin.create'"
          size="mini"
          type="success"
          plain
          icon="el-icon-plus"
          @click="handleCreate"
        >
          创建新账号
        </el-button>
      </div>
    </div>
    <div class="main">
      <el-table
        :row-style="{height: '20px'}"
        :cell-style="{padding: '3px 0'}"
        :loading="table.loading"
        style="width: 100%;height: 73vh"
        :data="table.data"
      >
        <el-table-column type="selection" width="55" align="center" />
        <el-table-column prop="id" label="编号" />
        <el-table-column prop="name" label="名称" align="center" width="200" show-overflow-tooltip />
        <el-table-column prop="account" label="账号" align="center" width="200" show-overflow-tooltip />
        <el-table-column prop="status" label="状态" align="center" width="200">
          <template slot-scope="{row}">
            <el-switch
              :disabled="!hasPermission('admin.update')"
              :active-value=0
              :inactive-value=-1
              v-model="row.status"
              active-color="#13ce66"
              inactive-color="#ff4949"
              @change="updateStatusChange(row)"
            >
            </el-switch>
          </template>
        </el-table-column>
        <el-table-column prop="remark" label="备注" align="center" width="200" show-overflow-tooltip />
        <el-table-column prop="loginTime" label="上次登录时间" align="center" width="160" />
        <el-table-column prop="createTime" label="账号创建时间" align="center" width="160" />
        <el-table-column label="操作" align="center" width="200">
          <template slot-scope="{row}">
            <el-button v-permission="'admin.update'" style="font-size: 14px;color: #2ecc71" size="medium" type="text"
                       @click="handleUpdate(row)">
              编辑
            </el-button>
            <el-dropdown trigger="click" style="margin-left: 10px" @command="handleDropdown($event,row)">
              <el-button size="mini" type="text" icon="el-icon-d-arrow-right">更多</el-button>
              <el-dropdown-menu slot="dropdown">
                <el-dropdown-item v-role="'超级管理员'" command="重置密码">
                  <span style="color:#f39c12;">
                    重置密码
                  </span>
                </el-dropdown-item>
                <el-dropdown-item command="分配角色" v-permission="'admin.giveRole'">
                  <span style="color: #2ed573">
                    分配角色
                  </span>
                </el-dropdown-item>
                <el-dropdown-item command="删除账号" v-permission="'admin.delete'">
                  <span style="color: #ff6b81">
                    删除账号
                  </span>
                </el-dropdown-item>
              </el-dropdown-menu>
            </el-dropdown>
          </template>
        </el-table-column>
      </el-table>
    </div>
    <div class="footer">
      <div style="text-align: center">
        <el-pagination
          background
          :page-size="table.pageSize"
          layout="sizes, prev, pager, next, jumper,->,total"
          :total="table.pageCount"
          :page-count="table.pages"
          :current-page="table.pageNo"
          @current-change="pageChange"
        >
        </el-pagination>
      </div>
    </div>

    <div>
      <el-dialog
        :title="dialog.title"
        :visible.sync="dialog.visible"
        :close-on-click-modal=false
        width="31%"
      >
        <el-form ref="dialogForm" :model="dialog.form" size="mini" :rules="dialog.rules">
          <el-form-item label="用户名称" prop="name">
            <el-input v-model="dialog.form.name" placeholder="请输入名称" style="width: 430px" maxlength="20"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="登录账号" prop="account" v-show="!isUpdateAdminInfo">
            <el-input v-model="dialog.form.account" placeholder="登录账号" style="width: 430px" maxlength="30"
                      show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="登录密码" prop="password" v-show="!isUpdateAdminInfo">
            <el-input v-model="dialog.form.password" placeholder="登录密码" style="width: 430px"
                      show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="rePassword" v-show="!isUpdateAdminInfo">
            <el-input v-model="dialog.form.rePassword" placeholder="确认密码" style="width: 430px"
                      show-password></el-input>
          </el-form-item>
          <el-form-item label="管理员邮箱" prop="email">
            <el-input v-model="dialog.form.email" placeholder="管理员邮箱" style="width: 430px"
                      maxlength="50" show-word-limit></el-input>
          </el-form-item>
          <el-form-item label="备注" prop="remark">
            <el-input
              type="textarea"
              placeholder="备注"
              v-model="dialog.form.remark"
              maxlength="255"
              show-word-limit
              :autosize=true
            >

            </el-input>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button size="small" type="primary" @click="commit">确 定</el-button>
          <el-button size="small" type="info" @click="dialog.visible = false">取 消</el-button>
        </template>
      </el-dialog>
      <el-dialog
        :title="dialog1.title"
        :visible.sync="dialog1.visible"
        :close-on-click-modal=false
        width="30%"
      >
        <el-form ref="resetPwdForm" :model="dialog1.form" size="mini" :rules="dialog1.rules">
          <el-form-item label="登录密码" prop="password">
            <el-input v-model="dialog1.form.password" placeholder="登录密码" style="width: 430px"
                      show-password></el-input>
          </el-form-item>
          <el-form-item label="确认密码" prop="rePassword">
            <el-input v-model="dialog1.form.rePassword" placeholder="确认密码" style="width: 430px"
                      show-password></el-input>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button size="small" type="primary" @click="reqResetPwd">确 定</el-button>
          <el-button size="small" type="info" @click="dialog1.visible = false">取 消</el-button>
        </template>
      </el-dialog>
      <el-dialog
        :title="dialog2.title"
        :visible.sync="dialog2.visible"
        :close-on-click-modal=false
        width="30%"
      >
        <el-form ref="giveRoleForm" :model="dialog2.form" size="mini">
          <el-form-item label="名称">
            <el-input v-model="dialog2.adName" :disabled="true" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="账号">
            <el-input v-model="dialog2.adAccount" :disabled="true" style="width: 400px"></el-input>
          </el-form-item>
          <el-form-item label="角色">
            <el-select
              style="width: 450px"
              v-model="dialog2.form.roleIds"
              multiple
              filterable
              clearable
              placeholder="请选择角色"
            >
              <el-option
                v-for="item in dialog2.options"
                :key="item.id"
                :label="item.roleName"
                :value="item.id"
              >
              </el-option>
            </el-select>
          </el-form-item>
        </el-form>
        <template slot="footer">
          <el-button size="small" type="primary" @click="reqGiveRole">确 定</el-button>
          <el-button size="small" type="info" @click="dialog2.visible = false">取 消</el-button>
        </template>
      </el-dialog>
    </div>
  </div>
</template>

<style scoped>
.header {
  margin: 10px 0;
}

.main {
  margin: 10px 0;
}

/deep/ .el-table th {
  background-color: #ecf0f1 !important;
  font-size: 15px;
  color: #2f3542;
  font-weight: bold !important;
}
</style>